package com.bbs.toutiao.controller.client;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.bbs.toutiao.aspect.SysLog;
import com.bbs.toutiao.exception.BaseException;
import com.bbs.toutiao.exception.ExceptionEnum;
import com.bbs.toutiao.service.client.impl.ArticleEditServiceImpl;
import com.bbs.toutiao.utils.Result;
import com.bbs.toutiao.vo.article.ArticlePageRequestVo;
import com.bbs.toutiao.vo.article.ArticleVo;
import com.bbs.toutiao.vo.comm.PageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.websocket.server.PathParam;

/**
 * 描述: 文章编辑
 * 作者： zhangBin
 * 时间： 2023/10/9 12:53
 * 版本： 1.0
 */

@Slf4j
@RestController
@RequestMapping("/api/article")
public class ArticleEditorController {

    @Resource
    ArticleEditServiceImpl articleEditService;


    /**
     * 发布文章
     * @param articleVo
     * @return
     */
    @PostMapping("/insert")
    public Result insertArticle(@RequestBody ArticleVo articleVo) {

        try {
            Assert.notBlank(articleVo.getArticleTitle());
            Assert.notBlank(articleVo.getArticle_text());
            Assert.notBlank(articleVo.getDataCategory());
            Assert.isTrue(articleVo.getClassId() > 0);
            Assert.isTrue(articleVo.getCreateUserId() > 0);
        } catch (Exception e) {
            return Result.error(404, "发布的文章不能为空");
        }
        //判断数组是否为空
        if (!ArrayUtil.isEmpty(articleVo.getCoverImg())) {
            articleVo.setImg(JSONUtil.toJsonStr(articleVo.getCoverImg()));
        }
        if (articleEditService.addArticle(articleVo) > 0) {
            return Result.success("文章发布成功");
        }
        return Result.error(400, "文章发布失败");
    }

    /**
     * 客户端动态查询文章
     *
     * @param requestVo
     * @return
     */
    @SysLog("用户获取了资讯列表")
    @PostMapping("/articleSelectQuery")
    public Result articlesQuery(@RequestBody ArticlePageRequestVo requestVo) {

        if (requestVo.getPage() < 1 && requestVo.getSize() < 1) {
            return Result.error(401, "请求的数据格式错误");
        }
        requestVo.setPage(requestVo.getPage(), requestVo.getSize());
        PageVo<ArticleVo> userList = articleEditService.articleSelectQuery(requestVo);
        return Result.success("查询成功", userList);
    }

    /**
     * 根据用户id分页查询文章
     * @param requestVo
     * @return
     */
    @PostMapping("/articlesByUserId")
    public Result articlesByUserId(@RequestBody ArticlePageRequestVo requestVo) {

        if (requestVo.getPage() < 1 && requestVo.getSize() < 1&&requestVo.getCreateUserId()>0) {
            return Result.error(401, "请求的数据格式错误");
        }
        requestVo.setPage(requestVo.getPage(), requestVo.getSize());
        PageVo<ArticleVo> userList = articleEditService.articleSelectQueryByUserId(requestVo);
        return Result.success("查询成功", userList);
    }

    /**
     * 用户删除文章
     */
    @GetMapping("/delete/{id}")
    public Result deleteArticle(@PathVariable("id") int id,@RequestHeader("token") String token) {
        int userId;
        try {
            JWT jwt = JWTUtil.parseToken(token);
            userId = Integer.parseInt(jwt.getPayload("userId").toString());
        } catch (Exception e) {
            throw new BaseException(ExceptionEnum.TOKEN_FONT_ERROR);
        }

        return articleEditService.deleteArticle(id,userId)==1?Result.success("删除成功"):Result.error(400,"删除失败");
    }


    /**
     * 分页查询用户个数
     * @param page
     * @param size
     * @param userName
     * @param userId
     * @return
     */
    @GetMapping("/userSearch/{page}/{size}")
    public Result userSearch(@PathVariable("page") int page,
                             @PathVariable("size") int size,
                             @PathParam("userName") String userName,
                             @PathParam("userId") int userId){

        int pages = (page-1)*size;
        return Result.success("查询成功", articleEditService.searchUser(pages,size,userName,userId));
    }
}
